package com.fingard.dsp.bank.directbank.mtcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @ClassName MTCB01Transaction
 * @Author Zhengzy
 * @Date 2019/12/19 9:33
 * @Version 1.0
 **/
public class MTCB01Transaction extends MTCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        // 历史明细返回给ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            // 按自然月查询
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                // 判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    // 跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                // 赋值通用参数
                MTCB01Header bankHeader = new MTCB01Header();
                bankHeader.trCode = "2001110";
                bankHeader.reqNo = p_req7516.reqHeader.reqSeqID;
                bankHeader.fileFlag = "0";// 文件标识 0-报文   1-文件

                // 发送给银行报文的xml对象
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                writeCommonHeader(xmlTextWriter, bankHeader);

                // 写报文体
                XElement tmpXElement = new XElement("body", "");
                tmpXElement.addChild(new XElement("acno", p_req7516.actNum));// 账号
                tmpXElement.addChild(new XElement("cur_code", convertCurToBank(p_req7516.actCur)));// 币种
                tmpXElement.addChild(new XElement("start_date", Format.Date8Format.format(tmpCalendarFrom.getTime())));// 起始日期
                tmpXElement.addChild(new XElement("end_date", Format.Date8Format.format(tmpCalendarTo.getTime())));// 终止日期
                xmlTextWriter.writeXElement(tmpXElement);
                xmlTextWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());

                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/body/ret_info");
                        if ("0000".equals(tmpRetCode)) {
                            int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));// 记录条数 视记录数而定
                            int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));// 字段数 视域数而定
                            if (tmpRecordNum > 0) {
                                String tmpDataMFS = null;
                                String tmpFileFlag = tmpBkReader.getFirstText("/ap/head/file_flag");
                                if ("1".equals(tmpFileFlag)) {
                                    String tmpBatchFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                                    // 下载共享目录批量查询文件
                                    String downloadFilePath = trimEndFileSp(bankFront.bkTransFolder) + File.separator;// 共享目录位置
                                    String p_FileFullPath = getTempFileDirectory() + File.separator + Format.Time6Format.format(new Date());// 下载到本地的路径
                                    StringBuilder p_sb = new StringBuilder();
                                    if (SmbFileUtil.smbDownload(p_FileFullPath, downloadFilePath, tmpBatchFileName, p_sb) == 1) {
                                        WriteBankLogLn("共享目录文件，位于：" + downloadFilePath);
                                        WriteBankLogLn("文件下载成功，位于" + p_FileFullPath);
                                        p_FileFullPath = p_FileFullPath + File.separator + tmpBatchFileName;
                                        tmpDataMFS = FileHelper.readFileText(p_FileFullPath, getCharset());
                                    } else {
                                        retAts.writeRespCode("-1");
                                        retAts.writeRespInfo(p_sb.toString());
                                        retAts.writeEnd();
                                        return retAts;
                                    }

                                    if (tmpDataMFS == null) {
                                        this.WriteBankLogLn("读取前置数据文件返回为null，需确认前置文件夹配置和文件是否存在");
                                    } else {
                                        this.WriteBankLogStep3(tmpDataMFS);
                                    }
                                } else {
                                    tmpDataMFS = tmpBkReader.getFirstText("/ap/body/serial_recode");
                                }
                                if (tmpDataMFS != null) {
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum + 1, tmpSbLog);
                                    if (tmpSbLog.length() == 0) {
                                        /*平台流水号0|账号1|货币码2|交易日期3|交易时间交易日期4|主机流水号5|交易行号6|户名7|对方账号8|对方货币码9|对方账号户名10|
                                        对方账号开户行11|对方行号12|交易类别13|钞汇标志14|他行标志15|同城异地标志16|手续费17|交易来源18|发生额标志19|
                                        被冲销流水号20|原交易日期21|现转标志22|借贷标志23|交易金额24|余额25|上笔余额26|冻结金额27|凭证种类28|凭证批次号29|
                                        凭证号码30|交易码31|柜员号32|传票号33|摘要34|附言35|交易时间戳36|备注字段一37|备注字段二38|交易行名39|行号40|
                                        打印次数41|支出金额42|收入金额43|*/
                                        for (int i = 1; i < tmpArrayList.size(); i++) {
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            //String[] tmpEachArr = {"平台流水0","账号1","货币码2","交易日期3","交易时间交易日期4","主机流水号5","交易行号6","户名7","对方账号8","对方货币码9","对方账号户名10","对方账号开户行11","对方行号12","交易类别13","钞汇标志14","他行标志15","同城异地标志16","手续费17","交易来源18","发生额标志19","被冲销流水号20","原交易日期21","现转标志22","借贷标志23","交易金额24","余额25","上笔余额26","冻结金额27","凭证种类28","凭证批次号29","凭证号码30","交易码31","柜员号32","传票号33","摘要34","附言35","交易时间戳36","备注字段一37","备注字段二38","交易行名39","行号40","打印次数41","支出金额42","收入金额43"};
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            tmpRetDetail.actArea = p_req7516.actArea;// 银行地区区域码
                                            tmpRetDetail.actNum = p_req7516.actNum;// 银行账号
                                            tmpRetDetail.recAccNum = tmpEachArr[8].trim();// 对方账号
                                            tmpRetDetail.recAccName = tmpEachArr[10].trim();// 对方户名
                                            String tmpRecBank = StringHelper.convertToDBC(tmpEachArr[11].trim());
                                            tmpRetDetail.recAccBank = tmpRecBank;// 对方开户银行
                                            // 交易日期
                                            if (tmpEachArr[3].length() == 8) {
                                                tmpRetDetail.tranDate = tmpEachArr[3].substring(0, 4) + "-" + tmpEachArr[3].substring(4, 6) + "-" + tmpEachArr[3].substring(6, 8);
                                            }
                                            // 交易时间
                                            if (tmpEachArr[4].length() >= 14) {
                                                tmpRetDetail.tranTime = tmpEachArr[4].substring(0, 4) + "-" + tmpEachArr[4].substring(4, 6) + "-" + tmpEachArr[4].substring(6, 8) + " " + tmpEachArr[4].substring(8, 10) + ":" + tmpEachArr[4].substring(10, 12) + ":" + tmpEachArr[4].substring(12, 14);
                                            } else {
                                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tmpEachArr[4].substring(0, 2) + ":" + tmpEachArr[4].substring(2, 4) + ":" + tmpEachArr[4].substring(4, 6);
                                            }
                                            tmpRetDetail.valueDate = tmpRetDetail.tranDate;// 起息日期
                                            tmpRetDetail.accBal = tmpEachArr[25];// 账号余额
                                            tmpRetDetail.postTimestamp = tmpEachArr[36];// 时间戳
                                            double tranAmt = Double.parseDouble(tmpEachArr[24].trim());
                                            if ("C".equals(tmpEachArr[23])) {
                                                if (tranAmt < 0) {
                                                    tmpRetDetail.cdFlag = "1";
                                                } else {
                                                    tmpRetDetail.cdFlag = "2";// 借贷标志 1：借（支出）， 2：贷（收入）
                                                }
                                            } else if ("D".equals(tmpEachArr[23])) {
                                                if (tranAmt < 0) {
                                                    tmpRetDetail.cdFlag = "2";
                                                } else {
                                                    tmpRetDetail.cdFlag = "1";
                                                }
                                            }
                                            tmpRetDetail.tranAmt = Math.abs(tranAmt) + "";// 交易金额
                                            tmpRetDetail.billType = tmpEachArr[28];// 票据类型
                                            tmpRetDetail.billNum = tmpEachArr[30];// 票据号码
                                            tmpRetDetail.usage = tmpEachArr[34];// 用途（摘要）
                                            tmpRetDetail.comment = tmpEachArr[35];// 备注（附言）
                                            tmpRetDetail.reqBatchNO = tmpEachArr[29];// 支付批号（29凭证批次号）
                                            tmpRetDetail.cur = this.convertCurToATS(tmpEachArr[2]);// 币种
                                            tmpRetDetail.originator = tmpEachArr[0];// 银行返回流水号
                                            nodeAnalysic(tmpEachArr, tmpRetDetail, getCharset());
                                            retAts.writeRetDetail(tmpRetDetail);
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbLog.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "数据为空";
                                }
                            }
                        } else {
                            // 9999，1102未知，需查证
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetInfo;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);// 下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            retAts.writeEnd();
            return retAts;
        }
        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        tmpReq7516.higherLevelAct = p_req7515.higherLevelAct;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}

